package com.example.demo.ds;


public class MyHashMap <K, V> {

    //如果用到泛型的话，记住涉及的类要重写一些方法，如equals 和 hashCode
    //以及在特定位置补上自己的哈希方法
    static class Node<K, V> {

        public K key;

        public V val;
        public Node<K, V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node<K, V>[] array;
    public int useSize;
    public static final double LOAD_FACTOR = 0.75;//"全局"常数

    public int hashMethod(K key) {
        return Math.abs(key.hashCode()) % array.length;
    }

    public int hashMethod(K key, int length) {
        return Math.abs(key.hashCode()) % length;
    }

    public MyHashMap() {
        array = (Node<K,V>[])(new Node[10]);
    }
    public void put(K key, V val) {
        int index = hashMethod(key);
        Node<K, V> cur = array[index];
        while(cur != null) {
            if(cur.key.equals(key)) {
                cur.val = val;
                return;
            }else {
                cur = cur.next;
            }
        }
        Node<K, V> newOne = new Node<>(key, val);
        newOne.next = array[index];
        array[index] = newOne;
        useSize++;
        if(calculateLoadFactor() > LOAD_FACTOR) {
            resize();
        }
    }

    private void resize() {

        Node<K, V>[] newArr = (Node<K,V>[]) (new Node[array.length * 2]);
        for (int i = 0; i < array.length; i++) {
            while(array[i] != null) {
                int index = hashMethod(array[i].key, newArr.length);
                Node<K, V> cur = newArr[index];
                Node<K, V> newOne = new Node<>(array[i].key, array[i].val);
                if(cur == null) {
                    newArr[index] = newOne;
                }else {
//  尾插               while(cur.next != null) {
//                        cur = cur.next;
//                    }
//                    cur.next = new Node(array[i].key, array[i].val);
                    // 头插法
                    newOne.next = cur;
                    newArr[index] = newOne;
                }
                array[i] = array[i].next;
            }
        }
        array = newArr;
    }

    private double calculateLoadFactor() {
        return useSize * 1.0 / array.length;
    }
    public V get(K key) {
        int index = hashMethod(key);
        Node<K, V> cur = array[index];
        while(cur != null) {
            if(cur.key.equals(key)) {
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
}
